package com.example.ivideo_2211a

import androidx.lifecycle.viewModelScope
import com.example.common.mvi.BaseViewModel
import com.example.common.mvi.SingleEvent
import com.example.common.mvi.NetworkResult
import kotlinx.coroutines.launch

class VideoDetailViewModel : BaseViewModel<VideoDetailIntent, VideoDetailViewState, VideoDetailResult>() {
    private val repository = VideoDetailRepository()
    override fun initialState(): VideoDetailViewState = VideoDetailViewState()

    override suspend fun handleIntent(intent: VideoDetailIntent) {
        when (intent) {
            is VideoDetailIntent.LoadVideoDetail -> loadVideoDetail(intent.videoId)
        }
    }

    private fun loadVideoDetail(videoId: Int) {
        viewModelScope.launch {
            repository.getVideoDetail(videoId).collect {
                when (it) {
                    is NetworkResult.Loading -> {
                        updateState(currentState().copy(isLoading = true, error = null))
                    }
                    is NetworkResult.Success -> {
                        updateState(
                            currentState().copy(
                                isLoading = false,
                                videoDetail = it.data,
                                error = null
                            )
                        )
                    }
                    is NetworkResult.Error -> {
                        updateState(
                            currentState().copy(
                                isLoading = false,
                                error = it.exception.message ?: "加载失败: 未知错误"
                            )
                        )
                        sendEvent(SingleEvent.ShowError(it.exception.message ?: "加载失败: 未知错误"))
                    }
                    else -> {
                        updateState(
                            currentState().copy(
                                isLoading = false,
                                error = "未知错误类型"
                            )
                        )
                    }
                }
            }
        }
    }
}